import { interpreter } from "@/api/request";
import { paidServiceList, payment, wxpayment } from "@/api/vip";
import { AIToken, Token } from "@/utils/cache";
import debounce from "@/utils/debounce";
import isWeChat from "@/utils/isWechat";
import toPayPage from "@/utils/toPayPage";
import { onMounted, ref } from "vue";
import Qrcode from "qrcode";
import { useUserInfo } from "@/store/user";

export default function userPay() {
  const { getUserInfo } = useUserInfo();

  const payPopup = ref();
  const code = ref();
  const meal = ref<any>({
    list: [],
    activeIndex: 0
  });
  const getMeal = async () => {
    const [err, res] = await interpreter(paidServiceList());
    if (!err) {
      meal.value.list = res.sort((a: any, b: any) => b.price - a.price);
    }
  };

  const selectMeal = (index: number) => {
    meal.value.activeIndex = index;
  };

  const onPay = debounce(async () => {
    const targetMeal = meal.value.list[meal.value.activeIndex];
    if (targetMeal) {
      if (!Token.get() || !AIToken.get()) {
        uni.showModal({
          title: "温馨提示",
          content: "您还未登录，是否前往登录",
          success(res) {
            if (res.confirm) {
              uni.redirectTo({ url: `/pages/login/login` });
            }
          }
        });
        return;
      }
      const [err, res] = await interpreter(payment(targetMeal.id));
      if (!err) {
        // https://robot.lnkyeah.com/bill/nowxpay?bill_id=8
        // const targetPage = `${window.location.origin}?orderId=${res.order_id}${window.location.hash}`;

        // #ifdef MP-WEIXIN
        const [err, wxRes] = await interpreter(wxpayment(res.order_id));
        if (!err) {
          const params = JSON.parse(wxRes.json);
          uni.requestPayment({
            ...params,
            success(res: any) {
              if (res.errMsg === "requestPayment:ok") {
                // 更新用户信息
                getUserInfo();
                uni.showToast({
                  title: "支付成功"
                });
              }
            }
          });
        } else {
          uni.showToast({
            title: "发起支付失败",
            icon: "none"
          });
        }
        // #endif

        // #ifdef H5
        const url = toPayPage(res.url, {
          order_id: res.order_id,
          redirect_url: "/pages/mine/mine"
        });
        console.log(url);
        if (!isWeChat()) {
          const res = await Qrcode.toDataURL(url, {
            correctLevel: "H"
          });
          if (typeof res === "string") {
            code.value = res;
            payPopup.value.open();
          } else {
            uni.showToast({
              title: "生成二维码失败",
              icon: "none"
            });
          }

          return;
        }
        window.location.href = url;

        // #endif
      } else {
        uni.showToast({
          title: "支付失败",
          icon: "none"
        });
      }
    }
  });

  onMounted(async () => {
    getMeal();
  });

  const handleClose = () => {
    payPopup.value.close();
  };
  return {
    payPopup,
    code,
    meal,
    selectMeal,
    getMeal,
    onPay,
    handleClose
  };
}
